package io.terminus.spzx.manager.utils;

import cn.hutool.core.date.DateUtil;
import com.google.common.base.Throwables;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.terminus.spzx.manager.properties.MinioProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 文件上传工具类
 * @Date 2024-05-26
 */
@Slf4j
public class FileUploadUtil {

    /**
     * 上传文件
     *
     * @param uploadFile      文件
     * @param minioProperties minIO配置信息
     * @return 文件路径
     */
    public static String uploadFile(MultipartFile uploadFile, MinioProperties minioProperties) {
        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            // 判断桶是否存在, 不存在就创建一个新的桶
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                // 如果存在打印信息
                log.info("Bucket: {} already exists.", minioProperties.getBucketName());
            }

            // 设置存储对象名称: yyyyMMdd/UUID-原文件名
            String fileName = DateUtil.format(new Date(), "yyyyMMdd") + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + uploadFile.getOriginalFilename();
            log.info("upload file name: {}", fileName);

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(uploadFile.getInputStream(), uploadFile.getSize(), -1)
                    .object(fileName)
                    .build();
            minioClient.putObject(putObjectArgs);

            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception except) {
            log.error("file upload exception, except info={}", Throwables.getStackTraceAsString(except));
            throw new RuntimeException(except);
        }
    }
}
